package com.polaris.live.dialog

import android.content.Context
import android.view.MotionEvent
import android.view.animation.AnticipateOvershootInterpolator
import com.blankj.utilcode.util.ScreenUtils
import com.bumptech.glide.Glide
import com.lxj.xpopup.core.CenterPopupView
import com.polaris.live.R
import com.polaris.live.common.manager.CoroutineScopeManager
import com.polaris.live.databinding.DialogLiveLuckBackpackGiftBinding
import com.polaris.live.im.sfs.bean.live.payload.InviteGiftPayloadBean
import com.polaris.live.utils.image.ImageUtils
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * 背包幸运礼物
 *
 * @author Created by 半仙 on 2024/5/30/030 16:58
 */
class LiveBackPackLuckGiftDialog(
    context: Context,
    private val mPayload: InviteGiftPayloadBean,
    private val mKey: Long,
    private val mOnDismissCallback: (mKey: Long) -> Unit,
) : CenterPopupView(context) {

    private lateinit var mBinding: DialogLiveLuckBackpackGiftBinding

    private var mDismissJob: Job? = null

    override fun getImplLayoutId() = R.layout.dialog_live_luck_backpack_gift

    override fun onCreate() {
        super.onCreate()
        mBinding = DialogLiveLuckBackpackGiftBinding.bind(popupImplView)
        mBinding.csBg.post {
            val marginTop = (ScreenUtils.getScreenHeight() * 0.2).toInt()
            val params = mBinding.csBg.layoutParams as LayoutParams
            params.setMargins(0, marginTop, 0, 0)
            mBinding.csBg.layoutParams = params

            mBinding.tvGiftNum.text = "${mPayload.gift.giftName}x${mPayload.reward?.times}"
            Glide.with(context).load(ImageUtils.imgPath(mPayload.gift.pic)).into(mBinding.ivGiftImg)
        }

        mBinding.root.scaleX = 0f
        mBinding.root.scaleY = 0f
        mBinding.root.alpha = 0f

        mBinding.root.post {
            mBinding.root.animate()
                .scaleX(1f)
                .scaleY(1f)
                .alpha(1f)
                .setDuration(610)
                .setInterpolator(AnticipateOvershootInterpolator(2.1f))
                .start()
        }


        mDismissJob = CoroutineScopeManager.mainScope.launch {
            delay(3000)
            dismiss()
        }
    }

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        return false
    }

    override fun dismiss() {
        mDismissJob?.cancel()
        mDismissJob = null
        mOnDismissCallback.invoke(mKey)
        super.dismiss()
    }
}